import React, { useState } from 'react'
import { clsx } from 'clsx'
import { Button, IconButton } from './Button'
import { Session } from '../../stores/chatStore'
import { formatRelativeTime } from '../../utils/timeGrouping'
import { EditIcon, DeleteIcon, ChevronRightIcon, CheckIcon } from './Icon'

interface SessionGroupProps {
  label: string
  icon?: string
  sessions: Session[]
  currentSessionId?: string
  onSessionSelect: (session: Session) => void
  onSessionEdit: (session: Session) => void
  onSessionDelete: (sessionId: string) => void
  onToggleFavorite?: (sessionId: string) => void
  className?: string
}

export const SessionGroup: React.FC<SessionGroupProps> = ({
  label,
  icon,
  sessions,
  currentSessionId,
  onSessionSelect,
  onSessionEdit,
  onSessionDelete,
  onToggleFavorite,
  className = ''
}) => {
  const [isExpanded, setIsExpanded] = useState(true)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)

  if (sessions.length === 0) return null

  return (
    <div className={clsx('mb-4', className)}>
      {/* 分组标题 */}
      <div 
        className="flex items-center justify-between px-3 py-2 cursor-pointer rounded-lg transition-all hover:scale-[1.01]"
        style={{
          borderRadius: 'var(--radius-md)'
        }}
        onClick={() => setIsExpanded(!isExpanded)}
        onMouseEnter={(e) => {
          e.currentTarget.style.background = 'var(--gray-50)'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.background = 'transparent'
        }}
      >
        <div className="flex items-center gap-2">
          <span style={{ fontSize: 'var(--text-sm)' }}>{icon}</span>
          <span style={{ fontSize: 'var(--text-sm)', fontWeight: 500, color: 'var(--gray-700)' }}>{label}</span>
          <span className="px-2 py-0.5 rounded-full" style={{
            fontSize: 'var(--text-xs)',
            color: 'var(--gray-500)',
            background: 'var(--gray-100)',
            borderRadius: 'var(--radius-full)'
          }}>
            {sessions.length}
          </span>
        </div>
        <div className={clsx(
          'transform transition-transform duration-200',
          isExpanded ? 'rotate-90' : 'rotate-0'
        )} style={{ color: 'var(--gray-400)' }}>
          <span>▶</span>
        </div>
      </div>

      {/* 会话列表 */}
      {isExpanded && (
        <div className="space-y-2 mt-2">
          {sessions.map((session) => (
            <div
              key={session.id}
              className={clsx(
                'group relative mx-1 rounded-lg transition-all duration-200 cursor-pointer border',
                currentSessionId === session.id 
                  ? 'shadow-sm' 
                  : 'border-transparent hover:shadow-sm'
              )}
              style={{
                borderRadius: 'var(--radius-md)',
                background: currentSessionId === session.id 
                  ? 'var(--primary-50)' 
                  : 'transparent',
                borderColor: currentSessionId === session.id 
                  ? 'var(--primary-200)' 
                  : 'transparent'
              }}
              onClick={() => onSessionSelect(session)}
              onMouseEnter={(e) => {
                if (currentSessionId !== session.id) {
                  e.currentTarget.style.background = 'var(--gray-50)'
                }
              }}
              onMouseLeave={(e) => {
                if (currentSessionId !== session.id) {
                  e.currentTarget.style.background = 'transparent'
                }
              }}
            >
              <div className="px-3 py-3">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="truncate flex-1" style={{
                        fontSize: 'var(--text-sm)',
                        fontWeight: 500,
                        color: currentSessionId === session.id 
                          ? 'var(--primary-700)' 
                          : 'var(--gray-900)'
                      }}>
                        {session.title}
                      </h3>
                      {session.isFavorite && (
                        <span className="text-yellow-500 text-xs" title="已收藏">
                          ⭐
                        </span>
                      )}
                    </div>
                    <div className="mt-1.5 flex items-center gap-2">
                      <span className="px-2 py-0.5 rounded-full" style={{
                        fontSize: 'var(--text-xs)',
                        background: 'var(--gray-100)',
                        color: 'var(--gray-600)',
                        borderRadius: 'var(--radius-full)'
                      }}>
                        {session.model === 'gpt-4' ? 'GPT-4' : session.model === 'gpt-3.5-turbo' ? '豆包' : session.model}
                      </span>
                      <span style={{ fontSize: 'var(--text-xs)', color: 'var(--gray-500)' }}>
                        {formatRelativeTime(session.updated_at)}
                      </span>
                    </div>
                  </div>
                  
                  {/* 操作菜单 */}
                  <div className="opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                    <div className="flex gap-1">
                      {onToggleFavorite && (
                        <button
                          className="p-1.5 rounded-md transition-all hover:scale-110"
                          style={{
                            borderRadius: 'var(--radius-sm)',
                            color: session.isFavorite ? '#f59e0b' : 'var(--gray-500)'
                          }}
                          title={session.isFavorite ? "取消收藏" : "收藏"}
                          onClick={(e) => {
                            e.stopPropagation()
                            onToggleFavorite(session.id)
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.background = session.isFavorite ? '#fef3c7' : '#fef3c7'
                            e.currentTarget.style.color = '#f59e0b'
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'transparent'
                            e.currentTarget.style.color = session.isFavorite ? '#f59e0b' : 'var(--gray-500)'
                          }}
                        >
                          {session.isFavorite ? '⭐' : '☆'}
                        </button>
                      )}
                      <button
                        className="p-1.5 rounded-md transition-all hover:scale-110"
                        style={{
                          borderRadius: 'var(--radius-sm)'
                        }}
                        title="重命名"
                        onClick={(e) => {
                          e.stopPropagation()
                          onSessionEdit(session)
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = 'var(--primary-100)'
                          e.currentTarget.style.color = 'var(--primary-600)'
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'transparent'
                          e.currentTarget.style.color = 'var(--gray-500)'
                        }}
                      >
                        ✏️
                      </button>
                      <button
                        className="p-1.5 rounded-md transition-all hover:scale-110"
                        style={{
                          borderRadius: 'var(--radius-sm)',
                          color: 'var(--gray-500)'
                        }}
                        title="删除"
                        onClick={(e) => {
                          e.stopPropagation()
                          setShowDeleteConfirm(session.id)
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = 'var(--error)'
                          e.currentTarget.style.color = 'white'
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'transparent'
                          e.currentTarget.style.color = 'var(--gray-500)'
                        }}
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 删除确认对话框 */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 max-w-sm w-full mx-4" style={{
            borderRadius: 'var(--radius-xl)',
            boxShadow: 'var(--shadow-lg)'
          }}>
            <h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 600, marginBottom: '8px' }}>确认删除</h3>
            <p style={{ color: 'var(--gray-600)', marginBottom: '16px', fontSize: 'var(--text-sm)' }}>
              删除后无法恢复，确定要删除这个会话吗？
            </p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setShowDeleteConfirm(null)}
                className="px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors"
                style={{
                  border: '1px solid var(--gray-200)',
                  borderRadius: 'var(--radius-md)',
                  fontSize: 'var(--text-sm)'
                }}
              >
                取消
              </button>
              <button
                onClick={() => {
                  onSessionDelete(showDeleteConfirm)
                  setShowDeleteConfirm(null)
                }}
                className="px-4 py-2 text-white rounded-lg hover:scale-[1.02] transition-all"
                style={{
                  background: 'var(--error)',
                  borderRadius: 'var(--radius-md)',
                  fontSize: 'var(--text-sm)'
                }}
              >
                删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

